import Vue from 'vue'
import Router from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue' // 新增登录页面

Vue.use(Router)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue'),
  },
  {
    path: '/wzlg',
    name: 'wzlg',
    component: () => import('../views/wzlgView.vue'),
    children: [
      {
        path: 'binhai',
        name: 'binhai',
        component: () => import('@/views/binhai.vue')
      },
    ]
  },
  {
    path: '/login', // 新增登录路由
    name: 'login',
    component: LoginView
  },
  {
    path: '/admin', // 新增管理员路由
    name: 'admin',
    component: () => import('../views/AdminView.vue'), // 新增管理员页面
    meta: { requiresAuth: true } // 添加路由元信息，表示需要登录
  }
]

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true' // 检查登录状态
  if (to.matched.some(record => record.meta.requiresAuth)) { // 如果目标路由需要登录
    if (!isAuthenticated) {
      next({ name: 'login' }) // 未登录则跳转到登录页面
    } else {
      next() // 已登录则继续
    }
  } else {
    next() // 不需要登录的路由直接放行
  }
})

export default router